package com.luck.ssoclient.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luo
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录便可访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }


    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token) {
        //ssoServer登录成功会在参数添加一个token,所以若不为空则表示已登录将用户信息添加到session当中
        if (StringUtils.isNotBlank(token)){
            //去请求ssoServer获取用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://127.0.0.1:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            //将用户信息放入session
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //若没登录,则重定向到sso服务端的登录页+原本请求的页面(当前写死)用于登录成功后继续访问该页面
            return "redirect:" + ssoServerUrl + "?redirect_url=http://127.0.0.1:8081/employees";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }

}
